package com.sfh.cpc.com;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.target.ImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.sfh.lib.AppCacheManager;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;

import java.io.File;
import java.security.MessageDigest;

/**
 * 功能描述:图片加载
 *
 * @author SunFeihu 孙飞虎
 * @date 2018/5/21
 */
public class ImageLoaderEngine {
    public interface ImageCallback {
        void onSuccess(BitmapDrawable bitmap);

        void onError(Exception e);
    }


    RequestBuilder requestBuilder;
    RequestOptions options;

    static {
        ImageViewTarget.setTagId(R.id.image_tag_1);
    }

    public ImageLoaderEngine(Context context, @NonNull int res) {
        this.requestBuilder = Glide.with(context).load(res);
        this.options = new RequestOptions();
    }

    public ImageLoaderEngine(Context context, @NonNull Uri uri) {
        if (uri != null) {
            this.requestBuilder = Glide.with(context).load(uri);
            this.options = new RequestOptions();
        }
    }

    public ImageLoaderEngine(Context context, @NonNull File file) {
        this.requestBuilder = Glide.with(context).load(file);
        this.options = new RequestOptions();
    }

    public ImageLoaderEngine(View view, @NonNull File file) {

        this.requestBuilder = Glide.with(view).load(file);
        this.options = new RequestOptions();
    }

    public ImageLoaderEngine(Context context, @NonNull String url) {
        this.requestBuilder = Glide.with(context).load(url);
        this.options = new RequestOptions();
    }

    public ImageLoaderEngine(View view, @NonNull String url) {
        this.requestBuilder = Glide.with(view).load(url);
        this.options = new RequestOptions();
    }

    /* --------------------------配置-------------------------------------------------*/
    public ImageLoaderEngine placeholder(@DrawableRes int placeholderResId) {
        this.options.placeholder(placeholderResId);
        return this;
    }

    public ImageLoaderEngine placeholder(@NonNull Drawable drawable) {
        this.options.placeholder(drawable);
        return this;
    }

    public ImageLoaderEngine centerInside() {
        this.options.centerInside();
        return this;
    }

    public ImageLoaderEngine roundTransform(int radius) {
        this.options.transform(new RoundedCorners(radius));
        return this;
    }

    public ImageLoaderEngine roundTransformCenterCrop(int radius) {
        this.options.transform(new CenterCrop(), new RoundedCorners(radius));
        return this;
    }

    public ImageLoaderEngine roundTransformCenterCropsBlur(int radius) {
        this.options.transform(new CenterCrop(), new RoundedCorners(radius), new BlurTransformation());
        return this;
    }

    public ImageLoaderEngine error(@DrawableRes int errorResId) {
        this.options.error(errorResId);
        return this;
    }


    public ImageLoaderEngine resizeDimen(@DimenRes int targetWidthResId, @DimenRes int targetHeightResId) {
        Application application = AppCacheManager.getApplication();
        int targetWidth = application.getResources().getDimensionPixelSize(targetWidthResId);
        int targetHeight = application.getResources().getDimensionPixelSize(targetHeightResId);
        this.resize(targetWidth, targetHeight);
        return this;
    }

    public ImageLoaderEngine resize(int targetWidth, int targetHeight) {
        this.options.override(targetWidth, targetHeight);
        return this;
    }

    public ImageLoaderEngine centerCrop() {
        this.options.centerCrop();
        return this;
    }


    public ImageLoaderEngine memoryPolicy() {
        this.options.skipMemoryCache(true);
        return this;
    }

    public void into(ImageView iv) {
        this.requestBuilder.apply(this.options).into(iv);
    }

    public void into(CustomTarget<Bitmap> iv) {
        this.requestBuilder.apply(this.options).into(iv);
    }

    public void into(ImageView iv, ImageCallback callback) {
        this.requestBuilder.addListener(new ImageCallbackImpl(callback)).apply(this.options).into(iv);
    }

    class ImageCallbackImpl implements RequestListener<BitmapDrawable> {

        ImageCallback callback;

        public ImageCallbackImpl(ImageCallback callback) {
            this.callback = callback;
        }

        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
            this.callback.onError(e);
            return false;
        }

        @Override
        public boolean onResourceReady(BitmapDrawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
            this.callback.onSuccess(resource);
            return false;
        }
    }

    class BlurTransformation extends BitmapTransformation {


        private static final int VERSION = 1;

        private static final String ID = "glide.transformations.BlurTransformation." + VERSION;


        private static final int MAX_RADIUS = 25;

        private static final int DEFAULT_DOWN_SAMPLING = 1;


        private int radius;

        private int sampling;


        public BlurTransformation() {

            this(MAX_RADIUS, DEFAULT_DOWN_SAMPLING);

        }

        @Override
        protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
            int width = toTransform.getWidth();

            int height = toTransform.getHeight();

            int scaledWidth = width / sampling;

            int scaledHeight = height / sampling;


            Bitmap bitmap = pool.get(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);


            Canvas canvas = new Canvas(bitmap);

            canvas.scale(1 / (float) sampling, 1 / (float) sampling);

            Paint paint = new Paint();

            paint.setFlags(Paint.FILTER_BITMAP_FLAG);

            canvas.drawBitmap(toTransform, 0, 0, paint);


            bitmap = blur(bitmap, radius, true);


            return bitmap;
        }


        public BlurTransformation(int radius) {

            this(radius, DEFAULT_DOWN_SAMPLING);

        }


        public BlurTransformation(int radius, int sampling) {

            this.radius = radius;

            this.sampling = sampling;

        }

        @Override

        public String toString() {

            return "BlurTransformation(radius=" + radius + ", sampling=" + sampling + ")";

        }


        @Override

        public boolean equals(Object o) {

            return o instanceof BlurTransformation &&

                    ((BlurTransformation) o).radius == radius &&

                    ((BlurTransformation) o).sampling == sampling;

        }


        @Override

        public int hashCode() {

            return ID.hashCode() + radius * 1000 + sampling * 10;

        }


        @Override

        public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

            messageDigest.update((ID + radius + sampling).getBytes(CHARSET));

        }


        public Bitmap blur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

            Bitmap bitmap;

            if (canReuseInBitmap) {
                bitmap = sentBitmap;
            } else {
                bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
            }

            if (radius < 1) {
                return (null);
            }

            int w = bitmap.getWidth();
            int h = bitmap.getHeight();

            int[] pix = new int[w * h];

            bitmap.getPixels(pix, 0, w, 0, 0, w, h);

            int wm = w - 1;
            int hm = h - 1;
            int wh = w * h;
            int div = radius + radius + 1;

            int r[] = new int[wh];
            int g[] = new int[wh];
            int b[] = new int[wh];

            int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
            int vmin[] = new int[Math.max(w, h)];

            int divsum = (div + 1) >> 1;
            divsum *= divsum;

            int dv[] = new int[256 * divsum];
            for (i = 0; i < 256 * divsum; i++) {
                dv[i] = (i / divsum);
            }
            yw = yi = 0;

            int[][] stack = new int[div][3];
            int stackpointer;
            int stackstart;
            int[] sir;
            int rbs;
            int r1 = radius + 1;
            int routsum, goutsum, boutsum;
            int rinsum, ginsum, binsum;

            for (y = 0; y < h; y++) {

                rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;

                for (i = -radius; i <= radius; i++) {

                    p = pix[yi + Math.min(wm, Math.max(i, 0))];
                    sir = stack[i + radius];
                    sir[0] = (p & 0xff0000) >> 16;
                    sir[1] = (p & 0x00ff00) >> 8;
                    sir[2] = (p & 0x0000ff);
                    rbs = r1 - Math.abs(i);
                    rsum += sir[0] * rbs;
                    gsum += sir[1] * rbs;
                    bsum += sir[2] * rbs;
                    if (i > 0) {
                        rinsum += sir[0];
                        ginsum += sir[1];
                        binsum += sir[2];

                    } else {

                        routsum += sir[0];
                        goutsum += sir[1];
                        boutsum += sir[2];
                    }
                }
                stackpointer = radius;

                for (x = 0; x < w; x++) {

                    r[yi] = dv[rsum];
                    g[yi] = dv[gsum];
                    b[yi] = dv[bsum];

                    rsum -= routsum;
                    gsum -= goutsum;
                    bsum -= boutsum;

                    stackstart = stackpointer - radius + div;
                    sir = stack[stackstart % div];

                    routsum -= sir[0];
                    goutsum -= sir[1];
                    boutsum -= sir[2];

                    if (y == 0) {
                        vmin[x] = Math.min(x + radius + 1, wm);
                    }

                    p = pix[yw + vmin[x]];
                    sir[0] = (p & 0xff0000) >> 16;
                    sir[1] = (p & 0x00ff00) >> 8;
                    sir[2] = (p & 0x0000ff);

                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];

                    rsum += rinsum;
                    gsum += ginsum;
                    bsum += binsum;

                    stackpointer = (stackpointer + 1) % div;
                    sir = stack[(stackpointer) % div];

                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];

                    rinsum -= sir[0];
                    ginsum -= sir[1];
                    binsum -= sir[2];
                    yi++;
                }
                yw += w;
            }

            for (x = 0; x < w; x++) {

                rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;

                yp = -radius * w;

                for (i = -radius; i <= radius; i++) {

                    yi = Math.max(0, yp) + x;


                    sir = stack[i + radius];


                    sir[0] = r[yi];

                    sir[1] = g[yi];

                    sir[2] = b[yi];


                    rbs = r1 - Math.abs(i);


                    rsum += r[yi] * rbs;

                    gsum += g[yi] * rbs;

                    bsum += b[yi] * rbs;


                    if (i > 0) {

                        rinsum += sir[0];

                        ginsum += sir[1];

                        binsum += sir[2];

                    } else {

                        routsum += sir[0];

                        goutsum += sir[1];

                        boutsum += sir[2];

                    }


                    if (i < hm) {

                        yp += w;

                    }

                }

                yi = x;

                stackpointer = radius;

                for (y = 0; y < h; y++) {

                    // Preserve alpha channel: ( 0xff000000 & pix[yi] )

                    pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];


                    rsum -= routsum;

                    gsum -= goutsum;

                    bsum -= boutsum;


                    stackstart = stackpointer - radius + div;

                    sir = stack[stackstart % div];


                    routsum -= sir[0];

                    goutsum -= sir[1];

                    boutsum -= sir[2];


                    if (x == 0) {

                        vmin[y] = Math.min(y + r1, hm) * w;

                    }

                    p = x + vmin[y];


                    sir[0] = r[p];

                    sir[1] = g[p];

                    sir[2] = b[p];


                    rinsum += sir[0];

                    ginsum += sir[1];

                    binsum += sir[2];


                    rsum += rinsum;

                    gsum += ginsum;

                    bsum += binsum;


                    stackpointer = (stackpointer + 1) % div;

                    sir = stack[stackpointer];


                    routsum += sir[0];

                    goutsum += sir[1];

                    boutsum += sir[2];


                    rinsum -= sir[0];

                    ginsum -= sir[1];

                    binsum -= sir[2];


                    yi += w;

                }

            }


            bitmap.setPixels(pix, 0, w, 0, 0, w, h);


            return (bitmap);

        }

    }
}
